package com.litidea.commons.config;

import static com.litidea.dao.DAOKeys.TABLE_START;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.litidea.dataobjects.BaseConfigDO;

@SuppressWarnings( { "unchecked" })
public class BaseConfig {

	static JdbcTemplate jdbc;

	private static List<BaseConfigDO> CONFIG_LIST;

	private static Map<String, String> CONFIG_K_V;

	private final static String GET_CONFIG_SQL = "select config_key,config_value,config_desc from "
			+ TABLE_START + "base_config";

	public static void initCache(JdbcTemplate jdbcTemplate) {
		jdbc = jdbcTemplate;
		refreshCache();
	}

	public static void refreshCache() {
		final Map<String, String> temp_k_v = new HashMap<String, String>(128);
		CONFIG_LIST = jdbc.query(GET_CONFIG_SQL, new RowMapper() {
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				BaseConfigDO baseConfig = new BaseConfigDO(rs
						.getString("config_key"), rs.getString("config_value"),
						rs.getString("config_desc"));
				temp_k_v.put(baseConfig.getKey(), baseConfig.getValue());
				return baseConfig;
			}
		});
		CONFIG_K_V = temp_k_v;
	}

	/**
	 * 获取基本信息列表
	 * 
	 * @return
	 */
	public static List<BaseConfigDO> getBaseConfigList() {
		checkBaseList();
		List<BaseConfigDO> tmpList = new ArrayList<BaseConfigDO>(CONFIG_LIST
				.size());
		for (BaseConfigDO config : CONFIG_LIST) {
			BaseConfigDO tmpConfig = new BaseConfigDO(config.getKey(), config
					.getValue(), config.getDesc());
			tmpList.add(tmpConfig);
		}
		return tmpList;
	}

	public static String getString(String key) {
		checkBaseList();
		return CONFIG_K_V.get(key);
	}

	public static Integer getInteger(String key) {
		String value = getString(key);
		return value == null ? null : Integer.valueOf(value);
	}

	public static Long getLong(String key) {
		String value = getString(key);
		return value == null ? null : Long.valueOf(value);
	}

	public static Double getDouble(String key) {
		String value = getString(key);
		return value == null ? null : Double.valueOf(value);
	}

	public static JSONObject getJSON(String key) {
		String value = getString(key);
		return value == null ? null : JSONObject.fromObject(value);
	}

	private static void checkBaseList() {
		if (CONFIG_LIST == null)
			throw new RuntimeException(
					"初始化基本配置信息失败，配置信息列表为空！");
	}

}
